package com.buddy.sds.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buddy.sds.auth.entity.SystemDepartment;
import com.buddy.sds.auth.entity.SystemRole;
import com.buddy.sds.auth.entity.SystemUser;
import com.buddy.sds.auth.mapper.ISystemUserMapper;
import com.buddy.sds.auth.service.ISystemDepartmentService;
import com.buddy.sds.auth.service.ISystemRoleService;
import com.buddy.sds.auth.service.ISystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Primary
@Service
public class SystemUserServiceImpl extends ServiceImpl<ISystemUserMapper, SystemUser> implements ISystemUserService {

    @Autowired
    private ISystemRoleService roleService;

    @Autowired
    private ISystemDepartmentService departmentService;

    @Override
    public SystemUser loadByUsername(String username,boolean withRoleAndPermission) {

        SystemUser user = baseMapper.selectOne(new QueryWrapper<SystemUser>().eq("user_name",username));

        if(user != null ){

            String depId = user.getUserDepartment();

            if(depId != null){

                //查询用户部门信息

                SystemDepartment systemDepartment = departmentService.getById(user.getUserDepartment());

                user.setDepartment(systemDepartment);

            }

            if(withRoleAndPermission){
                List<SystemRole> roles = roleService.getRoleListByUser(user.getUserId(),true);

                if(roles != null){

                    user.setRoles(roles);
                }
            }
        }

        return user;
    }

    @Override
    public boolean usernameExists(String username) {

        return baseMapper.existsUsername(username);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCascade(String userId) {
        //删除用户与角色关系
        baseMapper.deleteUserRoleByUser(userId);
        //删除用户
        baseMapper.deleteById(userId);
        //TODO 后期使用消息队列发布用户删除消息，业务系统订阅此通知进行后续操作
    }

    @Override
    public void updateUserRole(String userId, List<String> roleIdList) {

        List<SystemRole> oldRoles = roleService.getRoleListByUser(userId,false);

        List<String> newRols = new ArrayList<>(roleIdList);

        Iterator<SystemRole> it = oldRoles.iterator();

        while (it.hasNext()){

            SystemRole role = it.next();
            String roleId = role.getRoleId();

            if(newRols.contains(roleId)){
                //减去两个集合重复部分
                newRols.remove(roleId);
                it.remove();
            }
        }

        oldRoles.forEach(r->{
            baseMapper.deleteUserRoleByRole(r.getRoleId());
        });

        newRols.forEach(r->{

            String uuid = UUID.randomUUID().toString();

            baseMapper.addUserRole(uuid,userId,r);
        });
    }

    @Override
    public void updateUserPassword(String userId, String newPassword) {
        baseMapper.updatePasaword(userId,newPassword);
    }
}
